// 威胁情报中心-情报源管理数据

// 模拟情报源数据
const mockIntelligenceSources = [
  {
    id: '1',
    name: 'Dark Web监控',
    type: '暗网情报',
    qualityScore: 92,
    status: 'excellent', // excellent, good, normal, warning
    lastUpdated: '2024-07-15T10:30:00',
    updateFrequency: '实时',
    coverage: '全球',
    reliability: '高',
    factors: {
      timeliness: 95,
      hitRate: 90,
      diversity: 88,
      richness: 94,
      accuracy: 93
    }
  },
  {
    id: '2',
    name: 'APT组织追踪',
    type: '威胁组织',
    qualityScore: 87,
    status: 'good',
    lastUpdated: '2024-07-15T08:45:00',
    updateFrequency: '每日',
    coverage: '全球',
    reliability: '高',
    factors: {
      timeliness: 80,
      hitRate: 85,
      diversity: 92,
      richness: 88,
      accuracy: 90
    }
  },
  {
    id: '3',
    name: '漏洞情报平台',
    type: '漏洞数据库',
    qualityScore: 94,
    status: 'excellent',
    lastUpdated: '2024-07-15T11:20:00',
    updateFrequency: '实时',
    coverage: '全球',
    reliability: '极高',
    factors: {
      timeliness: 96,
      hitRate: 95,
      diversity: 90,
      richness: 93,
      accuracy: 96
    }
  },
  {
    id: '4',
    name: '恶意软件样本库',
    type: '恶意软件',
    qualityScore: 78,
    status: 'normal',
    lastUpdated: '2024-07-14T16:10:00',
    updateFrequency: '每日',
    coverage: '全球',
    reliability: '中',
    factors: {
      timeliness: 70,
      hitRate: 75,
      diversity: 85,
      richness: 80,
      accuracy: 78
    }
  },
  {
    id: '5',
    name: '威胁情报联盟',
    type: '共享情报',
    qualityScore: 82,
    status: 'good',
    lastUpdated: '2024-07-15T09:15:00',
    updateFrequency: '每日',
    coverage: '亚太',
    reliability: '中高',
    factors: {
      timeliness: 78,
      hitRate: 80,
      diversity: 88,
      richness: 79,
      accuracy: 82
    }
  },
  {
    id: '6',
    name: '沙箱分析服务',
    type: '动态分析',
    qualityScore: 76,
    status: 'normal',
    lastUpdated: '2024-07-15T07:30:00',
    updateFrequency: '实时',
    coverage: '全球',
    reliability: '中',
    factors: {
      timeliness: 85,
      hitRate: 72,
      diversity: 78,
      richness: 75,
      accuracy: 76
    }
  },
  {
    id: '7',
    name: '安全厂商通告',
    type: '官方公告',
    qualityScore: 90,
    status: 'excellent',
    lastUpdated: '2024-07-15T06:45:00',
    updateFrequency: '实时',
    coverage: '全球',
    reliability: '高',
    factors: {
      timeliness: 88,
      hitRate: 92,
      diversity: 85,
      richness: 89,
      accuracy: 93
    }
  },
  {
    id: '8',
    name: '社交媒体情报',
    type: '开源情报',
    qualityScore: 65,
    status: 'warning',
    lastUpdated: '2024-07-13T14:20:00',
    updateFrequency: '每日',
    coverage: '全球',
    reliability: '低',
    factors: {
      timeliness: 70,
      hitRate: 60,
      diversity: 75,
      richness: 68,
      accuracy: 62
    }
  }
];

// 模拟专题数据
const mockTopics = [
  {
    id: 't1',
    name: 'APT29活动监控',
    description: '针对APT29组织的最新活动和战术进行持续监控和分析',
    status: 'active',
    sources: [1, 2, 5, 7],
    newContentCount: 3,
    lastUpdated: '2024-07-15T09:30:00',
    keywords: ['APT29', 'Cozy Bear', '俄罗斯黑客', '国家支持'],
    pushFrequency: '实时',
    aiInsights: {
      summary: '近期APT29活动频率有所增加，主要针对政府机构和关键基础设施',
      keyFindings: ['使用新型钓鱼邮件技术', '利用未公开漏洞', '活动区域扩大到亚太地区'],
      recommendations: ['加强邮箱安全防护', '及时更新系统补丁', '部署高级威胁检测']
    }
  },
  {
    id: 't2',
    name: '勒索软件趋势',
    description: '全球勒索软件攻击趋势分析和预警',
    status: 'active',
    sources: [3, 4, 6, 8],
    newContentCount: 0,
    lastUpdated: '2024-07-15T08:15:00',
    keywords: ['勒索软件', '加密攻击', '双重勒索', 'REvil', 'LockBit'],
    pushFrequency: '每日',
    aiInsights: {
      summary: '勒索软件攻击手段持续演变，赎金要求呈上升趋势',
      keyFindings: ['双重勒索成为主流', '攻击目标转向中小型企业', '攻击工具自动化程度提高'],
      recommendations: ['定期数据备份', '实施网络分段', '员工安全意识培训']
    }
  },
  {
    id: 't3',
    name: '供应链攻击',
    description: '针对软件供应链的威胁情报监控',
    status: 'pending',
    sources: [2, 3, 7],
    newContentCount: 0,
    lastUpdated: '2024-07-14T15:45:00',
    keywords: ['供应链攻击', 'SolarWinds', 'Kaseya', '第三方组件'],
    pushFrequency: '每周',
    aiInsights: {
      summary: '供应链攻击复杂度不断提高，影响范围更广',
      keyFindings: ['攻击目标转向开发工具', '利用开源组件漏洞', '潜伏期延长'],
      recommendations: ['审计第三方供应商', '验证代码完整性', '加强开发环境安全']
    }
  },
  {
    id: 't4',
    name: 'DDoS攻击态势',
    description: '分布式拒绝服务攻击态势监控',
    status: 'active',
    sources: [1, 5, 8],
    newContentCount: 0,
    lastUpdated: '2024-07-15T10:45:00',
    keywords: ['DDoS', '拒绝服务', '流量攻击', '僵尸网络'],
    pushFrequency: '实时',
    aiInsights: {
      summary: 'DDoS攻击频率保持稳定，但攻击流量规模有所增加',
      keyFindings: ['反射放大攻击占比增加', '攻击持续时间延长', '针对游戏行业攻击增多'],
      recommendations: ['部署DDoS防护', '实施流量监控', '建立应急响应机制']
    }
  }
];

// 质量评估配置模型
const mockEvaluationModels = [
  {
    id: 'm1',
    name: '默认评估模型',
    description: '系统默认的情报源质量评估模型',
    factors: {
      timeliness: {
        weight: 25,
        delayThreshold: 60, // 分钟
        updateFrequency: 'daily',
        description: '情报的及时性评估'
      },
      hitRate: {
        weight: 20,
        historyStats: '0.85',
        falsePositiveRate: 0.1,
        description: '情报命中情况评估'
      },
      diversity: {
        weight: 15,
        dedupAlgorithm: 'cosine',
        similarityThreshold: 0.7,
        description: '情报独特性评估'
      },
      richness: {
        weight: 20,
        fieldCompleteness: 0.85,
        contextDepth: 'medium',
        description: '情报内容丰富度评估'
      },
      accuracy: {
        weight: 20,
        validationMethod: 'both', // auto, manual, both
        confidenceThreshold: 0.8,
        description: '情报准确性评估'
      }
    },
    createdAt: '2024-01-15T00:00:00',
    updatedAt: '2024-06-20T10:30:00',
    isDefault: true
  },
  {
    id: 'm2',
    name: '高敏感度评估模型',
    description: '针对高敏感度情报源的严格评估模型',
    factors: {
      timeliness: {
        weight: 30,
        delayThreshold: 15,
        updateFrequency: 'realtime',
        description: '情报的及时性评估'
      },
      hitRate: {
        weight: 25,
        historyStats: '0.9',
        falsePositiveRate: 0.05,
        description: '情报命中情况评估'
      },
      diversity: {
        weight: 15,
        dedupAlgorithm: 'jaccard',
        similarityThreshold: 0.8,
        description: '情报独特性评估'
      },
      richness: {
        weight: 15,
        fieldCompleteness: 0.95,
        contextDepth: 'high',
        description: '情报内容丰富度评估'
      },
      accuracy: {
        weight: 15,
        validationMethod: 'manual',
        confidenceThreshold: 0.9,
        description: '情报准确性评估'
      }
    },
    createdAt: '2024-03-10T00:00:00',
    updatedAt: '2024-07-05T14:20:00',
    isDefault: false
  }
];

// 本地存储管理函数
class DataManager {
  constructor() {
    this.initializeData();
  }

  // 初始化数据，如果本地存储为空则使用模拟数据
  initializeData() {
    if (!localStorage.getItem('intelligenceSources')) {
      localStorage.setItem('intelligenceSources', JSON.stringify(mockIntelligenceSources));
    }
    if (!localStorage.getItem('topics')) {
      localStorage.setItem('topics', JSON.stringify(mockTopics));
    }
    if (!localStorage.getItem('evaluationModels')) {
      localStorage.setItem('evaluationModels', JSON.stringify(mockEvaluationModels));
    }
  }

  // 获取所有情报源
  getIntelligenceSources() {
    return JSON.parse(localStorage.getItem('intelligenceSources') || '[]');
  }

  // 获取单个情报源
  getIntelligenceSource(id) {
    const sources = this.getIntelligenceSources();
    return sources.find(source => source.id === id);
  }

  // 保存情报源
  saveIntelligenceSource(source) {
    const sources = this.getIntelligenceSources();
    const index = sources.findIndex(s => s.id === source.id);
    if (index >= 0) {
      sources[index] = source;
    } else {
      sources.push(source);
    }
    localStorage.setItem('intelligenceSources', JSON.stringify(sources));
  }

  // 获取所有专题
  getTopics() {
    return JSON.parse(localStorage.getItem('topics') || '[]');
  }

  // 获取单个专题
  getTopic(id) {
    const topics = this.getTopics();
    return topics.find(topic => topic.id === id);
  }

  // 保存专题
  saveTopic(topic) {
    const topics = this.getTopics();
    const index = topics.findIndex(t => t.id === topic.id);
    if (index >= 0) {
      topics[index] = topic;
    } else {
      topics.push(topic);
    }
    localStorage.setItem('topics', JSON.stringify(topics));
  }

  // 获取所有评估模型
  getEvaluationModels() {
    return JSON.parse(localStorage.getItem('evaluationModels') || '[]');
  }

  // 获取单个评估模型
  getEvaluationModel(id) {
    const models = this.getEvaluationModels();
    return models.find(model => model.id === id);
  }

  // 保存评估模型
  saveEvaluationModel(model) {
    const models = this.getEvaluationModels();
    const index = models.findIndex(m => m.id === model.id);
    if (index >= 0) {
      models[index] = model;
    } else {
      models.push(model);
    }
    localStorage.setItem('evaluationModels', JSON.stringify(models));
  }

  // 重置所有数据
  resetData() {
    localStorage.removeItem('intelligenceSources');
    localStorage.removeItem('topics');
    localStorage.removeItem('evaluationModels');
    this.initializeData();
  }
  
  // 检查是否有指定类型的数据
  hasData(dataType) {
    const data = JSON.parse(localStorage.getItem(dataType) || '[]');
    return data && data.length > 0;
  }
  
  // 导出数据为JSON
  exportData(dataType = 'all') {
    let exportData = {};
    
    if (dataType === 'all') {
      // 导出所有数据
      exportData = {
        intelligenceSources: this.getIntelligenceSources(),
        topics: this.getTopics(),
        evaluationModels: this.getEvaluationModels(),
        exportTime: new Date().toISOString(),
        version: '1.0'
      };
    } else if (['intelligenceSources', 'topics', 'evaluationModels'].includes(dataType)) {
      // 导出指定类型的数据
      exportData = {
        [dataType]: this[`get${dataType.charAt(0).toUpperCase() + dataType.slice(1)}`](),
        exportTime: new Date().toISOString(),
        version: '1.0'
      };
    } else {
      throw new Error(`不支持的数据类型: ${dataType}`);
    }
    
    return JSON.stringify(exportData, null, 2);
  }
}

// 导出数据管理器实例
const dataManager = new DataManager();

// 辅助函数：格式化时间
function formatTime(dateString) {
  const date = new Date(dateString);
  const now = new Date();
  const diffMs = now - date;
  const diffMins = Math.floor(diffMs / 60000);
  const diffHours = Math.floor(diffMs / 3600000);
  const diffDays = Math.floor(diffMs / 86400000);

  if (diffMins < 1) return '刚刚';
  if (diffMins < 60) return `${diffMins}分钟前`;
  if (diffHours < 24) return `${diffHours}小时前`;
  if (diffDays < 7) return `${diffDays}天前`;
  return date.toLocaleDateString('zh-CN');
}

// 辅助函数：获取状态样式
function getStatusStyles(status) {
  switch (status) {
    case 'excellent':
      return {
        color: 'text-green-600',
        bgColor: 'bg-green-50',
        borderColor: 'border-green-200',
        label: '优秀'
      };
    case 'good':
      return {
        color: 'text-blue-600',
        bgColor: 'bg-blue-50',
        borderColor: 'border-blue-200',
        label: '良好'
      };
    case 'normal':
      return {
        color: 'text-yellow-600',
        bgColor: 'bg-yellow-50',
        borderColor: 'border-yellow-200',
        label: '一般'
      };
    case 'warning':
      return {
        color: 'text-red-600',
        bgColor: 'bg-red-50',
        borderColor: 'border-red-200',
        label: '需关注'
      };
    default:
      return {
        color: 'text-gray-600',
        bgColor: 'bg-gray-50',
        borderColor: 'border-gray-200',
        label: '未知'
      };
  }
}